package cc.yiueil.authenticationprovider;

import cc.yiueil.entity.UserEntity;
import cc.yiueil.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserEntity userEntity = userService.getUserByUsernameAndPassword(username, password);
        // 这里偷懒使用的明文Encoder进行匹配
        if (NoOpPasswordEncoder.getInstance().matches(password, userEntity.getPassword())) {
            return new UsernamePasswordAuthenticationToken(
                    username,
                    password,
                    Collections.emptyList()
            );
        } else {
            throw new BadCredentialsException("Authentication failed");
        }
    }

    // 判断当前的provider是否支持认证
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
